package com.bhs.sansonglogistics.ui.login;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.NumberKeyListener;
import android.util.ArrayMap;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.face.api.ZIMCallback;
import com.alipay.face.api.ZIMFacade;
import com.alipay.face.api.ZIMFacadeBuilder;
import com.alipay.face.api.ZIMResponse;
import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.base.BaseBean;

import com.bhs.sansonglogistics.base.MyApplication;
import com.bhs.sansonglogistics.bean.Authentication;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.ui.enterprise.EnterpriseCertificationActivity;
import com.bhs.sansonglogistics.utils.IDCard;
import com.bhs.sansonglogistics.utils.LogUtils;
import com.bhs.sansonglogistics.utils.SharedPreferencesUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.google.gson.Gson;

import java.text.ParseException;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 实名认证
 */
public class RealNameAuthenticationActivity extends BaseActivity implements TextWatcher, NetCallBack, View.OnClickListener {

    private TextView mTvSkip;
    private EditText mEtName;
    private EditText mEtIdNumber;
    private Button mBtnSubmit;
    private String uid;

    @Override
    public int initLayout() {
        return R.layout.activity_real_name_authentication;
    }

    @Override
    public void initView() {
        ZIMFacade.install(MyApplication.getContext());
        mTvSkip = findViewById(R.id.tv_skip);
        mEtName = findViewById(R.id.et_name);
        mEtIdNumber = findViewById(R.id.et_id_number);
        mBtnSubmit = findViewById(R.id.btn_submit);
        mEtName.addTextChangedListener(this);
        mEtIdNumber.addTextChangedListener(this);
        mTvSkip.setOnClickListener(this);
        mBtnSubmit.setOnClickListener(this);
        uid = SharedPreferencesUtils.getString(mActivity, "uid");
    }

    @Override
    public void initData() {
        if (!getIntent().getBooleanExtra("type", false)) {
            mTvSkip.setVisibility(View.GONE);
        }
        //限制限制Edittext只输入身份证号包含的字符
        mEtIdNumber.setKeyListener(new NumberKeyListener() {
            @Override
            public int getInputType() {
                return android.text.InputType.TYPE_CLASS_PHONE;
            }

            @Override
            protected char[] getAcceptedChars() {
                char[] numberChars = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'X'};
                return numberChars;
            }
        });

    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        verify();
    }

    private void verify() {
        boolean verify = true;
        if (TextUtils.isEmpty(mEtName.getText())) {
            verify = false;
        }
        if (TextUtils.isEmpty(mEtIdNumber.getText())) {
            verify = false;
        }

        mBtnSubmit.setEnabled(verify);
        mBtnSubmit.setBackgroundColor(verify ? Color.parseColor("#485EF4") : Color.parseColor("#7F485EF4"));
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.tv_skip) {
            startActivity(new Intent(mActivity, EnterpriseCertificationActivity.class));
        } else {
            try {
                if (!IDCard.IDCardValidate(mEtIdNumber.getText().toString())) {
                    ToastUtil.show("身份证号码格式错误");
                    return;
                }
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            //上传用户信息
            networkRequest(netApi.peopleApprove(mEtName.getText().toString(), mEtIdNumber.getText().toString()), this);
            Map<String, String> map = new ArrayMap<>();
            map.put("unid", uid);
            map.put("metaInfo", ZIMFacade.getMetaInfos(MyApplication.getContext()));
            map.put("truename", mEtName.getText().toString());
            map.put("cardno", mEtIdNumber.getText().toString());
            map.put("platform", "logistics");
            //人脸验证初始化
            networkRequest(netApi.get_init_face_verify(map), this, 888);
        }
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 0) {
            BaseBean bean = new Gson().fromJson(json, BaseBean.class);
        } else if (requestCode == 888) {
            Authentication bean = new Gson().fromJson(json, Authentication.class);
            ToastUtil.show(bean.getMsg());
            if (bean.isStatus()) {
                LogUtils.d(bean.getData().getCertifyId());
                // 开始验证
                ZIMFacade zimFacade = ZIMFacadeBuilder.create(getApplicationContext());
                zimFacade.verify(bean.getData().getCertifyId(), true, null, new ZIMCallback() {
                    @Override
                    public boolean response(final ZIMResponse response) {
                        if (1000 == response.code) {
                            LogUtils.d("认证成功。");
                            Map<String, String> map = new ArrayMap<>();
                            map.put("unid", uid);
                            map.put("CertifyId", bean.getData().getCertifyId());
                            map.put("face_sn", bean.getData().getFace_sn());
                            networkRequest(netApi.get_describe_face_verify(map), RealNameAuthenticationActivity.this, 999);
                        } else {
                            ToastUtil.show("认证失败");
                        }
                        return true;
                    }
                });
            }
        } else if (requestCode == 999) {
            //认证结果
            Authentication bean = new Gson().fromJson(json, Authentication.class);
            ToastUtil.show(bean.getMsg());
            if (bean.isStatus()) {
                SharedPreferencesUtils.saveBoolean(mActivity, "is_approve", true);
                SharedPreferencesUtils.saveString(mActivity, "realName", mEtName.getText().toString());
                if (getIntent().getBooleanExtra("type", false)) {
                    startActivity(new Intent(mActivity, EnterpriseCertificationActivity.class));
                } else {
                    finish();
                }
            }
        }
    }

    @Override
    public void onFailure(int requestCode) {

    }
}